module IPFS.Multiaddr.IP(
    IP(..),
    ipv4,
    ipv6,
    Port(..),
    parsePort,
    encodePort,
    decodePort,
    toPort,
    toString
) where

import Prelude

import Data.BigInt as BI 
import Data.ByteString as BS
import Data.Integral (class Integral, fromIntegral, toBigInt)
import Data.Serialize.Get (Get, getWord16be)
import Data.Word (Word16, Word8, parseWord16, word16toBytes)
import IPFS.Multiaddr.IP.IPv4 (IPv4, fromOctets)
import IPFS.Multiaddr.IP.IPv6 (IPv6, fromWord16s)
import Text.Parsing.Parser (Parser)

data IP = IP4 IPv4 | IP6 IPv6


ipv4::Word8 -> Word8 -> Word8 -> Word8 -> IP
ipv4 a b c d = IP4 $ fromOctets a b c d

ipv6::Word16 -> Word16 -> Word16 -> Word16 -> Word16 -> Word16 -> Word16 -> Word16 -> IP
ipv6 a b c d e f g h = IP6 $ fromWord16s a b c d e f g h

type Port = Word16



toString::Port -> String  
toString p = BI.toBase 10 $ toBigInt p

toPort:: forall a. Integral a => Eq a => a ->  Port
toPort n  = fromIntegral n

fromPort::forall a.Integral a => Port -> a
fromPort p = fromIntegral p

parsePort::Parser String Port
parsePort = parseWord16

encodePort::Port -> BS.ByteString
encodePort p = word16toBytes p

decodePort::Get Port
decodePort =  getWord16be